import { getGlobalData } from "../../get-global-data";
enum EnInputType {
    input = 'input',
    picker = 'picker'
}
// components/popup/popup.js
Component({
    options: {
        styleIsolation: 'isolated'
    },
    /**
     * 组件的属性列表
     */
    properties: {
        bind: {
            type: Object
        },
        name: {
            type: String
        },
        type: {
            type: String,
            value: EnInputType.input
        },
        placeholder: {
            type: String
        },
        options: {
            type: Array,
            value: []
        },
        displayField: {
            type: String
        },
        valueField: {
            type: String
        },
        title: {
            type: String
        },
        label: {
            type: String
        }
    },

    /**
     * 组件的初始数据
     */
    data: {
        pickerIndex: -1,
        value: ''
    },

    lifetimes: {
        attached: function () {
        }
    },

    /**
     * 组件的方法列表
     */
    methods: {
        bindPickerChange: function (e: any) {
            this.setData({
                pickerIndex: e.detail.value
            });
        },
        onChange: function (e) {
            this.setData({
                value: e.detail.value,
            });
        },
        getItemFieldValue: function(item, field) {
            if (typeof item !== 'object') {
                return item;
            } else {
                return item[field];
            }
        },
        emitValue: function(v) {
            this.triggerEvent('changeValue', {
                name: this.data.name,
                value: v,
                option: this.data.options[this.data.pickerIndex] || null
            });
        },
        inputEvent: function(e) {
            this.emitValue(e.detail.value);
        }
    },
    observers: {
        pickerIndex: function (v) {
            const {options, valueField, type} = this.data;
            if (v > -1) {
                this.setData({
                    value: this.getItemFieldValue(options[v], valueField)
                });

            } else if (type === EnInputType.picker) {
                this.setData({
                    value: ''
                });
            }
        },
        value: function(v) {
            this.emitValue(v);
        }
    }
})
